<?php
namespace app\admin\controller;


use app\admin\model\JingFen;
use app\admin\model\MerchSetplus;
use app\admin\model\Setplus2;
use app\merchant\model\MerchantInfo;
use app\merchant\model\MerchantOrder;
use app\merchant\model\Order;
use think\facade\View;
use think\Request;
use app\admin\model\Alipay;

class UserWalletApply extends Base
{
    protected $ModelPath = 'UserWalletApply';
    protected $model = null;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->con = "UserWalletApply";
        $this->title = "用户提现";

        $module = $this->ModelPath;//strtolower($this->ModelPath);
        $this->model = new \app\admin\model\UserWalletApply();

        View::assign(array(
            'module' => $module,
            'title' => $this->title,
            'con' => $this->con,
            'pageSize' => $this->pageSize
        ));
    }

    public function index()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];
//            $this->model = $this->model
//                ->with(['userBank', 'userAlipay']);
//            $this->model = $this->model->where('merchant_id', $this->merchantId);
//            dd($params);
            $map[] = ['status', '=', $params['status']];

            if(isset($params['id'])){
                if(!empty($params['id'])){
                    $map[] = ['id', '=', $params['id']];
                }
            }
            if(isset($params['user_id'])){
                if(!empty($params['user_id'])){
                    $map[] = ['user_id', '=', $params['user_id']];
                }
            }

            if(isset($params['real_name'])){
                if(!empty($params['real_name'])){
//                    dd($params['real_name']);
//                    $userBank = \app\admin\model\UserBank::where('real_name', $params['real_name'])->find();
                    $userBankList = \app\admin\model\UserBank::where('real_name', 'like', '%' . $params['real_name'] . '%')->column('user_id');
//                    dd($userBankList);
                    if($userBankList){
//                        $map[] = ['user_id', '=', $userBank['user_id']];
                        $map[] = ['user_id', 'in', $userBankList];
                    }
                }
            }

            if(isset($params['phone'])){
                if(!empty($params['phone'])){
                    $list = \app\admin\model\User::where('phone', 'like', '%' . $params['phone'] . '%')->column('id');
                    if($list){
                        $map[] = ['user_id', 'in', $list];
                    }
                }
            }

//            if(isset($params['real_name'])){
//                if(!empty($params['real_name'])){
////                    $userBank = \app\admin\model\UserBank::where('real_name', $params['real_name'])->find();
//                    $userBankList = \app\admin\model\UserBank::whereLike('real_name', '%' . $params['real_name'] . '%')->column('user_id');
//                    if($userBankList){
////                        $map[] = ['user_id', '=', $userBank['user_id']];
//                        $map[] = ['user_id', 'in', $userBankList];
//                    }
//                }
//            }

            if(isset($params['time'])){
                if(!empty($params['time'])){
                    $timeArr = explode(' - ', $params['time']);
                    $map[] = ['create_time', '>=', $timeArr[0]];
                    $map[] = ['create_time', '<=', $timeArr[1]];
                }
            }

//            if(isset($params['team'])){
//                if(!empty($params['team'])){
//                    $userIds = (new \app\admin\model\User())->getAllChildren($params['team']);
//                    array_push($userIds, (int)$params['team']);
//                    $userIdsStr = implode(',', $userIds);
//                    //dd($userIdsStr);
//                    //dd($userIds);
//                    $map[] = ['user_id', 'in', $userIdsStr];
//                }
//            }
//
//            if(isset($params['type'])){
//                if(!empty($params['type'])){
//                    $map[] = ['type', '=', $params['type']];
//                }
//            }

            $totalAmount = 0;
            $totalAmount = \app\admin\model\UserWalletApply::where($map)
                ->sum('money');
            $total = \app\admin\model\UserWalletApply::where($map)->count();

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $this->model
//                ->with(['userWalletApplyUserBank'])
                ->where($map)
                ->order('id DESC')
                ->append([
                    'apply_type_format',
                    'apply_info_format'
                ])
//                    ->fetchSql()//
//                ->select()//;dd($list);
                ->limit($p, $pageSize)
                ->select();
//dd($list);
            $arr['totalRow']['id'] = '合计';
            $arr['totalRow']['money'] = $totalAmount;
            $arr['data'] = $list;
            $arr['code'] = 0;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            $status = request()->param('status', 0);
            View::assign(array(
                'status'        =>    $status,
            ));
            if($status == 0){
                return View::fetch('waiting');
            }else{
                return View::fetch();
            }
        }
    }

    public function exportExcel()
    {
        $params = request()->param();
        $map = [];

//        if(!empty($params['status'])){
//            $map[] = ['status', '=', $params['status']];
//        }
        $map[] = ['status', '=', 0];

        if(isset($params['id'])){
            if(!empty($params['id'])){
                $map[] = ['id', '=', $params['id']];
            }
        }
        if(isset($params['user_id'])){
            if(!empty($params['user_id'])){
                $map[] = ['user_id', '=', $params['user_id']];
            }
        }

        if(isset($params['time'])){
            if(!empty($params['time'])){
                $timeArr = explode(' - ', $params['time']);
                $map[] = ['create_time', '>=', $timeArr[0]];
                $map[] = ['create_time', '<=', $timeArr[1]];
            }
        }
//        $totalAmount = 0;
//        $totalAmount = \app\admin\model\UserWalletApply::where($map)
//            ->sum('money');
        $total = \app\admin\model\UserWalletApply::where($map)->count();

        $pageIndex = max(input('page'), 1);
        $pageSize = $this->pageSize;
        $p = ($pageIndex - 1) * $pageSize;

        $list = $this->model->with(['userWalletApplyUserBank'])
            ->where($map)
//            ->where('user_id', 50189)
            ->order('id DESC')
//            ->append(['real_name_format', 'card_no_format', 'bank_name_format', 'bank_no_format', 'content_format'])
            ->append(['content_format', 'money_format'])
//                    ->fetchSql()
//            ->limit($p, $pageSize)
            ->select();
//dd($list);
//        $arr['totalRow']['id'] = '合计';
//        $arr['totalRow']['money'] = $totalAmount;
        $arr['data'] = $list;
        $arr['code'] = 0;
        $arr['count'] = $total;
        $arr['limit'] = $pageSize;
        $arr['msg'] = "获取" . $this->title . "列表成功";
        return json($arr);
    }

    public function updateStatus()
    {
        if(request()->isPost()){
            $params = request()->param();

            $ids = $params['ids'];
//            dd($ids);
            $this->model->whereIn('id', $ids)->update([
                'status'=>2,
                'return_data'=>'打款成功'
            ]);

            $arr['status'] = 1;
            $arr['msg'] = '已处理';
            return json($arr);
        }
    }



    public function add(){
        if(request()->isPost()){
            $code = input('code');
            $codeArr = explode(',', $code);
            $sum = $codeArr[0] + $codeArr[1] + $codeArr[2] + $codeArr[3];
            $num = input('num');
            $add = [
                'time'         =>  input('time'),
                'num'     =>  $num,
                'code'     =>  $code,
                'sum'     =>  $sum,
                'status'     =>  1,
            ];

//            var_dump($add);die;

            $this->M->data($add);
            $result = $this->M->save();
            if ($result !== false) {
                (new \app\model\Num())->insert([
                    'name'=>(int)$num + 1,
                    'type'=>1,
                ]);
                $arr['status'] = 1;
                $arr['msg'] = '添加成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '添加失败';
            }
            return $arr;
        }else{
//            $numArr = Db::name('num')
//                ->where('type', 1)
//                ->order('id DESC')->select();
//            View::assign(array(
//                'numArr'        =>    $numArr,
//            ));
            return View::fetch();
        }
    }

    public function edit(){
        if(request()->isPost()){
            $params = request()->param();
            $update = $params;
            $update['withdraw_resp'] = '【' . ($this->admin)['username'] . '】打款成功';
            $status = 2;
            if($params['state'] == 'error'){
                $withdraw = $this->model->find($params['id']);
                $update['withdraw_resp'] = '【' . ($this->admin)['username'] . '】拒绝';
                $status = -1;
                //
                \app\api\model\User::induce($withdraw['user_id'], ($withdraw['money'] * 100), 'balance', 'withdrawal_return', $update['withdraw_resp']);
                \app\admin\model\UserBank::where('user_id', $withdraw['user_id'])->update([
                    'status'=>'disabled'
                ]);
            }

            $save = $this->model->where('id', $params['id'])->update([
                'status'=>$status,
                'return_data'=>$update['withdraw_resp']
            ]);
            if ($save) {
                $arr['status'] = 1;
                $arr['msg'] = '修改成功';
            } else {
                $arr['status'] = 0;
                $arr['msg'] = '修改失败';
            }
            return $arr;
        }else{
            $id = input('id');
            $info = $this->model->where('id', $id)->find();
            View::assign(array(
                'info'        =>    $info,
            ));
            return View::fetch();
        }
    }

    public function merchant_order()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            $orderList = MerchantOrder::where('merchant_id', $this->merchantId)
                ->where('status', 'payed');
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $list = $orderList
                // ->where($map)
                ->select();

            $total = count($list);

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $orderList
                // ->where($map)
                // ->where('rec',1)

                ->order('id DESC')
                ->append(['type_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            return View::fetch();
        }
    }

    public function order()
    {
//        var_dump($this->M->toArray());die;
        if(request()->isPost()){
            $params = request()->param();
            $map = [];

            $orderList = Order::where('merchant_id', $this->merchantId)
                ->where('status', 'payed');
//            if(isset($params['title'])){//return 1;
//                // $title = input('title');
//                $this->model = $this->model->where("title", "like", $params['title']);
//            }
//            if(isset($params['author_id'])){
//                // $authorId = input('author_id');var_dump(1);die;
//                $this->model = $this->model->where("author", "like", $params['author_id']);
//            }

//             if(input('tag_id')){
//                 $authorId = input('tag_id');
// //                $map['_string'] = 'FIND_IN_SET(' . $authorId . ', tag_list)';
//                 $map[] = ['exp', Db::raw("FIND_IN_SET(" . $authorId . ", tag_list)")];
//             }

            $list = $orderList
                // ->where($map)
                ->select();

            $total = count($list);

            $pageIndex = max(input('page'), 1);
            $pageSize = $this->pageSize;
            $p = ($pageIndex - 1) * $pageSize;

            $list = $orderList
                // ->where($map)
                // ->where('rec',1)

                ->order('id DESC')
                ->append(['type_format'])
                ->limit($p, $pageSize)
                ->select();
// var_dump($list);die;
            $arr['data'] = $list;
            $arr['code'] = 0;
            // var_dump(1);die;
            $arr['count'] = $total;
            $arr['limit'] = $pageSize;
            $arr['msg'] = "获取" . $this->title . "列表成功";
            return json($arr);
        }else{
            return View::fetch();
        }
    }

    //所有用户开户
    public function allUserOpen()
    {
//        $userBank = \app\admin\model\UserBank::where('user_id', 64)->find();

        $userBankList = \app\admin\model\UserBank::where('status', 'pending')->select();

        foreach ($userBankList as $userBank){
            $res = (new \app\admin\model\Setplus())->userOpen($userBank);
            if($res['respCode'] == '00'){
                if($res['status'] == 3){
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'status'=>'enabled'
                    ]);
                }
            }else{
                if($res['respCode'] == '94'){
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'status'=>'enabled'
                    ]);
                }else{
                    \app\admin\model\UserBank::where('id', $userBank['id'])->update([
                        'msg'=>$res['message']
                    ]);
                }
            }
        }
    }

    public function test()
    {
//        (new \app\admin\model\Setplus())->userOpen();
        (new \app\admin\model\Setplus())->withDraw();
    }

    //批量拒绝
    public function batchRefuse(){
        if(request()->isPost()){
            $params = request()->param();

            $ids = $params['ids'];

            foreach ($ids as $item)
            {
                $withdraw = \app\admin\model\UserWalletApply::where('id', $item)->find();
                $update = [];
                $update['withdraw_resp'] = '【' . ($this->admin)['username'] . '】拒绝';
                $status = -1;
                \app\api\model\User::induce($withdraw['user_id'], ($withdraw['money'] * 100), 'balance', 'withdrawal_return', $update['withdraw_resp']);//dd($item);
                \app\admin\model\UserWalletApply::where('id', $item)->update([
                    'status'=>$status,
                    'return_data'=>$update['withdraw_resp']
                ]);
            }

            $arr['status'] = 1;
            $arr['msg'] = '批量拒绝成功';
            return json($arr);
        }else{
            $arr['status'] = 0;
            $arr['msg'] = '批量拒绝失败';
            return json($arr);
        }
    }
}